<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
        <script type="text/javascript" src="lib/require.js"></script>
        <script type="text/javascript" src="lib/stats.js"></script>
    </head>
    <body>
        <style>
            body {
                margin:0px;
                background-color:#20242B;
                overflow: hidden;
            }
            #viewport {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
            }
        </style>
        <div id="viewport">
            <canvas id="main"></canvas>
        </div>
        <div id="time" style="position:absolute;left:10px;top:10px;color:white;"></div>
        <script type="text/javascript">
            require(['../dist/claygl', 'lib/webvr-polyfill'], function(clay){
                var Material = clay.Material;
                var Mesh = clay.Mesh;
                var Cube = clay.geometry.Cube;
                var meshUtil = clay.util.mesh;
                var timeline =  new clay.Timeline();

                timeline.start();

                var main = document.getElementById('main');
                var viewport = document.getElementById('viewport');
                var renderer = new clay.Renderer({
                    canvas: main
                });
                var scene = new clay.Scene;
                var camera = new clay.camera.Perspective({
                    aspect: renderer.getViewportAspect(),
                    far: 500
                });
                var stereoCamera = new clay.vr.StereoCamera();
                var distorter = new clay.vr.CardboardDistorter();

                var cube = new Cube();
                cube.generateTangents();
                var shader = clay.shader.library.get('clay.standard');
                var material = new Material({
                    shader: shader
                });
                material.set('glossiness', 0.4);
                var diffuse = new clay.Texture2D;
                diffuse.load("assets/textures/crate.gif");
                var normal = new clay.Texture2D;
                normal.load("assets/textures/normal_map.jpg");
                material.set('diffuseMap', diffuse);
                material.set('normalMap', normal);

                var root = new clay.Node();
                scene.add(root);
                var cubeMesh = new Mesh({
                    geometry: cube,
                    material: material
                });
                for( var i = 0; i < 10; i++){
                    for(var j = 0; j < 10; j++){
                        for( var k = 0; k < 10; k++){
                            var mesh = new clay.Mesh({
                                geometry: cube,
                                material: material
                            });
                            mesh.position.set(50 - Math.random() * 100, 50 - Math.random() * 100, 50-Math.random() * 100);
                            mesh.scale.set(1, 1, 1);
                            root.add(mesh);
                        }
                    }
                }
                var light = new clay.light.Point({
                    range: 200
                });
                scene.add(light);
                scene.add(new clay.light.Ambient({
                    intensity: 0.4
                }))

                camera.position.set(0, 0, 10);

                if (navigator.getVRDisplays) {
                    navigator.getVRDisplays().then(function (displays) {
                        if (displays.length > 0)  {
                            var vrDisplay = displays[0];
                            vrDisplay.requestPresent({
                                // source: renderer.canvas
                            }).then(function () {
                                start(vrDisplay);
                            }).catch(function () {
                                console.error('VRDisplay is not capable of presenting');

                                start();
                            });
                        }
                    }).catch(function () {
                        console.error('VRDisplay is not capable of presenting');

                        start();
                    });
                }
                else {
                    start();
                }


                var framebuffer = new clay.FrameBuffer();
                var sourceTexture = new clay.Texture2D();
                framebuffer.attach(sourceTexture);

                var debugPass = new clay.compositor.Pass({
                    fragment: clay.Shader.source('clay.compositor.output')
                });
                debugPass.setUniform('texture', sourceTexture);
                function start(vrDisplay) {

                    if (vrDisplay) {
                        distorter.updateFromVRDisplay(vrDisplay);
                    }

                    timeline.on('frame', function(deltaTime) {
                        var start = new Date().getTime();

                        if (vrDisplay) {
                            stereoCamera.updateFromVRDisplay(vrDisplay);
                        }
                        else {
                            camera.aspect = renderer.getWidth() / renderer.getHeight();
                            camera.update();
                            stereoCamera.updateFromCamera(camera);
                        }

                        framebuffer.bind(renderer);

                        renderer.clearBit = null;

                        renderer.gl.clear(renderer.gl.DEPTH_BUFFER_BIT | renderer.gl.COLOR_BUFFER_BIT);
                        renderer.setViewport(0, 0, renderer.getWidth() / 2, renderer.getHeight());
                        renderer.render(scene, stereoCamera.getLeftCamera());

                        renderer.setViewport(renderer.getWidth() / 2, 0, renderer.getWidth() / 2, renderer.getHeight());
                        renderer.render(scene, stereoCamera.getRightCamera());

                        framebuffer.unbind(renderer);

                        distorter.render(renderer, sourceTexture);
                        // debugPass.render(renderer);
                    });

                }

                function resize() {
                    renderer.resize(viewport.offsetWidth, viewport.offsetHeight);
                    sourceTexture.width = renderer.getWidth() * renderer.getDevicePixelRatio();
                    sourceTexture.height = renderer.getHeight() * renderer.getDevicePixelRatio();
                    sourceTexture.dirty();
                }

                window.addEventListener('resize', resize);

                resize();
            })

        </script>
    </body>
</html>